import {useStore} from 'vuex'
import {computed} from 'vue'
//购物车相关逻辑
export const uesCommonCartEffect=(shopId)=>{
    const store = useStore();
    const cartList=store.state.cartList;
    const changeCartItemInfo=(shopId,productId,productInfo,num)=>{
        store.commit('changeCartItemInfo',{shopId,productId,productInfo,num})
    }
    //获取购物车列表
    const productList=computed(()=>{
        const productList=cartList[shopId]?.productList || {}
        const notEmptyProductList={}
        for(let i in productList){
            const product=productList[i]
            if(product.count>0){
                notEmptyProductList[i]=product
            }
        }
        return notEmptyProductList
    })
    //取店铺名字
    const shopName=computed(()=>{
        const shopName=cartList[shopId]?.shopName || ''
        return shopName
    })
    //取总价
    const calculations=computed(()=>{
        const productList=cartList[shopId]?.productList
        //total:计算购物车数量,price:计算价格,allChecked:全选
        const result={total:0,price:0,allChecked:true}
        if(productList){
            for(let i in productList){
                const product = productList[i]
                result.total += product.count
                if(product.check){
                    result.price += product.count*product.price
                }
                if(product.count>0&&!product.check){
                    result.allChecked=false
                }
            }
        }
        result.price=result.price.toFixed(2)
        return result
    })
    return {changeCartItemInfo,cartList,productList,shopName,calculations}
}

